﻿using System;
using System.ComponentModel.Composition;
using log4net;
using log4net.Appender;
using log4net.Core;
using log4net.Repository.Hierarchy;

namespace AlanAamy.Net.TemperatureConverter.Services
{
    public interface IMemoryLogAppenderService
    {
        event EventHandler<MemoryLogEvent> LogAppend;
    }

    public class MemoryLogEvent : EventArgs
    {
        public LoggingEvent LoggingEvent { get; set; } 
    }

    [Export(typeof(IMemoryLogAppenderService))]
    [PartCreationPolicy(CreationPolicy.Shared)]
    class MemoryLogAppenderService : IMemoryLogAppenderService , IAppender
    {
        public event EventHandler<MemoryLogEvent> LogAppend = delegate { };

        [ImportingConstructor]
        public MemoryLogAppenderService()
        {
#pragma warning disable 618
            ((Hierarchy)LogManager.GetLoggerRepository()).Root.AddAppender(this); 
#pragma warning restore 618
        }

            public void Close()
            {
                //throw new NotImplementedException();
            }

            public void DoAppend(LoggingEvent loggingEvent)
            {
                LogAppend(this, e: new MemoryLogEvent { LoggingEvent = loggingEvent });
            }

            public string Name
            {
                get
                {
                    return "MemoryLogAppenderService";
                }
                set
                {
                    throw new NotImplementedException();
                }
            }            

    }
}
